import amqplib from 'amqplib'
const consume = async () => {
  const connection = await amqplib.connect({
    protocol: 'amqp',
    hostname: '192.168.18.101',
    port: 30209,
    username: 'iot',
    password: 'allsmart@iot',
    vhost: '/iot'
  });
  //  const connection = await amqplib.connect(`amqp://iot:allsmart@iot192.168.18.101:30209`)
  // const connection = await amqplib.connect('amqp://admin:password@192.168.11.201:30997')
  // const connection = await amqplib.connect('amqp://localhost:5672');
  const channel = await connection.createChannel(); //创建一个频道
  console.log('--------连接成功-------------');

  await channel.assertExchange('amq.topic', 'topic', {
    durable: true,
  });
  console.log('----------添加交换机--------------');
  //添加一个队列
  const { queue } = await channel.assertQueue('huarentong-subscription1', {
    durable: false,
  });
  console.log('------------添加队列---------------');
  //绑定交换机
  /**
   * @param {String} queue 队列名称
   * @param {String} exchange 交换机名称
   * @param {String} routingKey 路由键 *匹配一个单词 #匹配多个单词
   */
  //这儿变化了
  await channel.bindQueue(queue, 'amq.topic', '.data.iot2_0.#');
  channel.once('error', (error) => {
    if (error.code !== 404) {
      throw err;
    }
  });
  //接收消息
  channel.consume(
    'huarentong-subscription1',
    (msg) => {
      console.log(msg.content.toString());
    },
    {
      noAck: true, //自动确认消息被消费
    },
  );
}
consume();